<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace api\user\controller;

use app\admin\model\DeviceModel;
use app\admin\model\DeviceUserModel;
use app\portal\model\CommandModel;
use app\user\model\ItemModel;
use app\user\model\OrderModel;
use app\user\model\PetModel;
use app\user\model\UserCurrentDeivceModel;
use app\user\model\UserModel;
use cmf\controller\UserBaseController;
use cmf\lib\Storage;
use think\Db;
use think\Image;
use think\Validate;
use app\user\controller\WeixinController;

class ProfileController extends UserBaseController
{

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心首页
     */
    public function center()
    {
        $user = cmf_get_current_user();
        $this->assign($user);

        $userId = cmf_get_current_user_id();

        $userModel = new UserModel();
        $user = $userModel->where('id', $userId)->find();
        $this->assign('user', $user);
        return $this->fetch();
    }

    /**
     * 编辑用户资料
     */
    public function edit()
    {
        $user = cmf_get_current_user();
        $this->assign($user);
        return $this->fetch('edit');
    }

    /**
     * 编辑用户资料提交
     */
    public function editPost()
    {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'user_nickname' => 'max:32',
                'sex' => 'between:0,2',
                'birthday' => 'dateFormat:Y-m-d|after:-88 year|before:-1 day',
                'user_url' => 'url|max:64',
                'signature' => 'max:128',
            ]);
            $validate->message([
                'user_nickname.max' => lang('NICKNAME_IS_TO0_LONG'),
                'sex.between' => lang('SEX_IS_INVALID'),
                'birthday.dateFormat' => lang('BIRTHDAY_IS_INVALID'),
                'birthday.after' => lang('BIRTHDAY_IS_TOO_EARLY'),
                'birthday.before' => lang('BIRTHDAY_IS_TOO_LATE'),
                'user_url.url' => lang('URL_FORMAT_IS_WRONG'),
                'user_url.max' => lang('URL_IS_TO0_LONG'),
                'signature.max' => lang('SIGNATURE_IS_TO0_LONG'),
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $editData = new UserModel();
            if ($editData->editData($data)) {
                $this->success(lang('EDIT_SUCCESS'), "user/profile/center");
            } else {
                $this->error(lang('NO_NEW_INFORMATION'));
            }
        } else {
            $this->error(lang('ERROR'));
        }
    }

    /**
     * 个人中心修改密码
     */
    public function passwpassword()
    {
        $user = cmf_get_current_user();
        $this->assign($user);
        return $this->fetch();
    }

    /**
     * 个人中心修改密码提交
     */
    public function passwordPost()
    {
        if ($this->request->isPost()) {
            $validate = new Validate([
                // 'old_password' => 'require|min:6|max:32',
                'password' => 'require|min:6|max:32',
                'userid' => 'require',
                // 'repassword' => 'require|min:6|max:32',
            ]);
            $validate->message([
                // 'old_password.require' => lang('old_password_is_required'),
                // 'old_password.max' => lang('old_password_is_too_long'),
                // 'old_password.min' => lang('old_password_is_too_short'),
                'password.require' => lang('password_is_required'),
                'password.max' => lang('password_is_too_long'),
                'password.min' => lang('password_is_too_short'),
                'userid.require' => '用户id不能为空',
                // 'repassword.require' => lang('repeat_password_is_required'),
                // 'repassword.max' => lang('repeat_password_is_too_long'),
                // 'repassword.min' => lang('repeat_password_is_too_short'),
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                return json_encode([
                    'status' => true,
                    'msg' => $validate->getError(),
                ]);
            }

            $login = new UserModel();
            $log = $login->editPassword($data);
            switch ($log) {
                case 0:
                    // $this->success(lang('change_success'));
                    return json_encode([
                        'status' => true,
                        'msg' => lang('change_success'),
                    ]);
                    break;
                case 1:
                    // $this->error(lang('password_repeat_wrong'));
                    return json_encode([
                        'status' => false,
                        'msg' => lang('password_repeat_wrong'),
                    ]);
                    break;
                case 2:
                    // $this->error(lang('old_password_is_wrong'));
                    return json_encode([
                        'status' => false,
                        'msg' => lang('old_password_is_wrong'),
                    ]);
                    break;
                default:
                    // $this->error(lang('ERROR'));
                    return json_encode([
                        'status' => false,
                        'msg' => lang('ERROR'),
                    ]);
            }
        } else {
            // $this->error(lang('ERROR'));
            return json_encode([
                'status' => false,
                'msg' => lang('ERROR'),
            ]);
        }
    }

    // 用户头像编辑
    public function avatar()
    {
        $user = cmf_get_current_user();
        $this->assign($user);
        return $this->fetch();
    }

    // 用户头像上传
    public function avatarUpload()
    {
        $file = $this->request->file('file');
        $result = $file->validate([
            'ext' => 'jpg,jpeg,png',
            'size' => 1024 * 1024,
        ])->move('.' . DS . 'upload' . DS . 'avatar' . DS);

        if ($result) {
            $avatarSaveName = str_replace('//', '/', str_replace('\\', '/', $result->getSaveName()));
            $avatar = 'avatar/' . $avatarSaveName;
            session('avatar', $avatar);

            return json_encode([
                'code' => 1,
                "msg" => "上传成功",
                "data" => [
                    'file' => $avatar,
                ],
                "url" => '',
            ]);
        } else {
            return json_encode([
                'code' => 0,
                "msg" => $file->getError(),
                "data" => "",
                "url" => '',
            ]);
        }
    }

    // 用户头像裁剪
    public function avatarUpdate()
    {
        // $avatar = session('avatar');
        $avatar = $this->request->param("avatar", '', "string");
        if (!empty($avatar)) {
            $w = $this->request->param('w', 0, 'intval');
            $h = $this->request->param('h', 0, 'intval');
            $x = $this->request->param('x', 0, 'intval');
            $y = $this->request->param('y', 0, 'intval');

            $avatarPath = "./upload/" . $avatar;

            $avatarImg = Image::open($avatarPath);
            $avatarImg->crop($w, $h, $x, $y)->save($avatarPath);

            $result = true;
            if ($result === true) {
                $storage = new Storage();
                $result = $storage->upload($avatar, $avatarPath, 'image');

                $userId = cmf_get_current_user_id();
                Db::name("user")->where([
                    "id" => $userId,
                ])->update([
                    "avatar" => $avatar,
                ]);
                session('user.avatar', $avatar);
                $this->success("头像更新成功！");
            } else {
                $this->error("头像保存失败！");
            }
        }
    }

    /**
     * 绑定手机号或邮箱
     */
    public function binding()
    {
        $user = cmf_get_current_user();
        $this->assign($user);
        return $this->fetch();
    }

    /**
     * 绑定手机号
     */
    public function bindingMobile()
    {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'mobile' => 'require|number',
                'userid' => 'require',
                'verification_code' => 'require|number|max:6',
            ]);
            $validate->message([
                'mobile.require' => '手机号不能为空',
                'mobile.number' => '手机号只能为数字',
                // 'mobile.unique' => '手机号已存在',
                'verification_code.require' => '验证码不能为空',
                'userid.require' => 'userid不能为空',
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                return json_encode([
                    'status' => false,
                    'msg' => $validate->getError(),
                ]);
            }
            $errMsg = cmf_check_verification_code($data['mobile'], $data['verification_code']);
            if (!empty($errMsg)) {
                // $this->error($errMsg);
                return json_encode([
                    'status' => false,
                    'msg' => $errMsg,
                ]);
            }
            $userModel = new UserModel();
            $user = $userModel->where([
                'mobile' => $data['mobile'],
            ])->find();
            if ($user) {
                // return json_encode([
                // 'status' => false,
                // 'msg' => '手机号已经被绑定',
                // 'user' => $user
                // ]);
                // 合并之前的手机注册账号
                $pre_uid = $user['id'];
                $device_user_model = new DeviceUserModel();
                $device_user = $device_user_model->where([
                    'uid' => $pre_uid,
                ])->select();
                foreach ($device_user as $k => $v) {
                    $v['uid'] = $data['userid'];
                    $v->save();
                }

                $user_current_device_model = new UserCurrentDeivceModel();
                $user_current_device = $user_current_device_model->where([
                    'uid' => $data['userid'],
                ])->find();
                if (!$user_current_device) {
                    $user_current_device_pre = $user_current_device_model->where([
                        'uid' => $pre_uid,
                    ])->find();
                    if ($user_current_device_pre) {
                        $user_current_device_model->save([
                            'uid' => $data['userid'],
                            'd_id' => $user_current_device_pre['d_id'],
                        ]);
                        $user_current_device_pre->delete();
                    }
                }
                $user->delete();
            }
            $log = $userModel->bindingMobile($data);
            $user = $userModel->find($data['userid']);
            switch ($log) {
                case 0:
                    // $this->success('手机号绑定成功');
                    return json_encode([
                        'status' => true,
                        'msg' => '手机号绑定成功',
                        'user' => $user,
                    ]);
                    break;
                default:
                    return json_encode([
                        'status' => false,
                        'msg' => '未受理的请求',
                    ]);
                    // $this->error('未受理的请求');
            }
        } else {
            // $this->error("请求错误");
            return json_encode([
                'status' => false,
                'msg' => '请求错误',
            ]);
        }
    }

    /**
     * 绑定邮箱
     */
    public function bindingEmail()
    {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'username' => 'require|email|unique:user,user_email',
                'verification_code' => 'require',
            ]);
            $validate->message([
                'username.require' => '邮箱地址不能为空',
                'username.email' => '邮箱地址不正确',
                'username.unique' => '邮箱地址已存在',
                'verification_code.require' => '验证码不能为空',
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $errMsg = cmf_check_verification_code($data['username'], $data['verification_code']);
            if (!empty($errMsg)) {
                $this->error($errMsg);
            }
            $userModel = new UserModel();
            $log = $userModel->bindingEmail($data);
            switch ($log) {
                case 0:
                    $this->success('邮箱绑定成功');
                    break;
                default:
                    $this->error('未受理的请求');
            }
        } else {
            $this->error("请求错误");
        }
    }

    // 获取用户绑定的设备列表
    public function getDeviceList()
    {
        $status = true;
        $id = $this->request->param("uid", 0, "intval");
        if ($id == 0) {
            return json_encode([
                'status' => false,
                'msg' => '参数错误',
            ]);
        }
        // $device = DeviceUserModel::where('uid', $id)->select();
        $device = Db::table('erxi_device_user')->alias('a')
            ->join('erxi_device b', 'a.device_id = b.id')
            ->join('erxi_user_current_deivce c', "a.device_id=c.d_id and c.uid=$id", 'left')
            ->where([
                'a.uid' => $id,
                'a.status' => 1,
            ])
            ->field("b.*,c.d_id is_current,FROM_UNIXTIME(b.effect_time,'%Y.%m.%d') end_time")
            ->select();
        return json_encode([
            'status' => true,
            'msg' => '请求成功',
            'data' => $device,
        ]);
    }

    // 绑定用户微信
    public function bindWeixin()
    {
        $uid = $this->request->param("uid", 0, "intval");
        $code = $this->request->param("code", '', "string");
        if ($uid == 0 || $code == '') {
            return json_encode([
                'status' => false,
                'msg' => '参数错误',
            ]);
        }
        $user = UserModel::get($uid);
        if (!$user) {
            return json_encode([
                'status' => false,
                'msg' => '找不到用户',
            ]);
        }
        if (!$user['openid']) {
            $usermodel = new UserModel();
            $user['openid'] = $usermodel->bindWeixin($code);
            $user_o = UserModel::where('openid', $user['openid'])->find();
            if ($user_o) {
                return json_encode([
                    'status' => false,
                    'msg' => '绑定失败，此微信已经绑定',
                    'openid' => $user['openid'],
                ]);
            }
            $user->save();
            return json_encode([
                'status' => true,
                'msg' => '绑定成功',
                'openid' => $user['openid'],
            ]);
        }
        return json_encode([
            'status' => false,
            'msg' => '绑定失败',
        ]);
    }

    // 绑定用户微信
    public function unbindWeixin()
    {
        $uid = $this->request->param("uid", 0, "intval");
        if ($uid == 0) {
            return json_encode([
                'status' => false,
                'msg' => '参数错误',
            ]);
        }
        $user = UserModel::get($uid);
        if (!$user) {
            return json_encode([
                'status' => false,
                'msg' => '找不到用户',
            ]);
        }
        if ($user['openid']) {
            $usermodel = new UserModel();
            $user['openid'] = null;
            $user->save();
            return json_encode([
                'status' => true,
                'msg' => '解除绑定成功',
            ]);
        }
        return json_encode([
            'status' => false,
            'msg' => '解除绑定失败',
        ]);
    }

    // 用户绑定设备
    public function bindDevice()
    {
        $uid = $this->request->param("uid", 0, "intval");
        // $device_id = $this->request->param("device_id", 0, "intval");
        $imei = $this->request->param("imei", '', "string");
        if ($uid == 0 || $imei == '') {
            return json_encode([
                'status' => false,
                'msg' => '参数错误',
            ]);
        }
        $devicemodel = new DeviceModel();
        $device = $devicemodel->where([
            'imei' => $imei,
        ])->find();
        if (!$device) {
            return json_encode([
                'status' => false,
                'msg' => '设备没有注册',
            ]);
        }
        $data = [
            'imei' => $imei,
        ];
        $device_user_count = DeviceUserModel::where($data)->count();
        if ($device_user_count > 0) {
            return json_encode([
                'status' => false,
                'msg' => '设备已经被绑定',
            ]);
        }
        $duModel = new DeviceUserModel();
        $duModel->save([
            'imei' => $imei,
            'uid' => $uid,
            'device_id' => $device['id'],
            'status' => 1,
            'create_time' => time(),
        ]);

        $UserCurrentDeivceModel = new UserCurrentDeivceModel();
        $UserCurrentDeivce = $UserCurrentDeivceModel->where([
            'uid' => $uid,
        ])->find();
        if (!$UserCurrentDeivce) {
            $UserCurrentDeivceModel['uid'] = $uid;
            $UserCurrentDeivceModel['d_id'] = $device['id'];
            $UserCurrentDeivceModel->save();
        }

        return json_encode([
            'status' => true,
            'msg' => '绑定成功',
        ]);
    }

    // 接触用户绑定设备
    public function unbindDevice()
    {
        $uid = $this->request->param("uid", 0, "intval");
        $device_id = $this->request->param("device_id", 0, "intval");
        if ($uid == 0 || $device_id == 0) {
            return json_encode([
                'status' => false,
                'msg' => '参数错误',
            ]);
        }
        $data = [
            'device_id' => $device_id,
            'uid' => $uid,
        ];
        $duModel = new DeviceUserModel();
        $usercurrentdevice = new UserCurrentDeivceModel();
        $usercurrentdevice->where([
            'uid' => $uid,
            'd_id' => $device_id,
        ])->delete();
        $device_user = $duModel->where($data)->find();
        if (!$device_user) {
            return json_encode([
                'status' => false,
                'msg' => '设备没有被绑定',
            ]);
        }
        $device_user->delete();
        return json_encode([
            'status' => true,
            'msg' => '解除绑定成功',
        ]);
    }

    // 设置围栏范围
    public function setEnclosureRange()
    {
        $range = $this->request->param("range", 0, "intval");
        $latitude = $this->request->param("latitude");
        $longitude = $this->request->param("longitude");
        $device_id = $this->request->param("device_id", 0, "intval");
        if (!$device_id || !$latitude || !$longitude) {
            return json_encode([
                'status' => false,
                'msg' => '参数错误',
            ]);
        }
        // $data = ['device_id'=>$device_id,'range'=>$range,'imei'=>$imei];
        $device = DeviceModel::get($device_id);
        if (!$device) {
            return json_encode([
                'status' => false,
                'msg' => '找不到设备',
            ]);
        }
        if ($range) {
            $device['range'] = $range;
        }
        if ($latitude) {
            $device['center_latitude'] = $latitude;
        }
        if ($longitude) {
            $device['center_longitude'] = $longitude;
        }
        $device->save();
        return json_encode([
            'status' => true,
            'msg' => '设置成功',
        ]);
    }

    // 更新用戶位置
    public function updateUserLocation()
    {
        $latitude = $this->request->param("latitude", 0, "float");
        $longitude = $this->request->param("longitude", 0, "float");
        $imei = $this->request->param("imei", 0, "string");
        $device_model = new DeviceModel();
        $device = $device_model->where("imei", $imei)->find();
        if (!$device) {
            return json_encode([
                'status' => false,
                'msg' => 'device not found',
            ]);
        }
        $device['latitude'] = $latitude;
        $device['longitude'] = $longitude;
        $device->save();
    }

    // 设备围栏开关
    public function openclosuer()
    {
        $status = $this->request->param("status", 0, "int");
        $imei = $this->request->param("imei", 0, "string");
        $device_model = new DeviceModel();
        $device = $device_model->where("imei", $imei)->find();
        if (!$device) {
            return json_encode([
                'status' => false,
                'msg' => 'device not found',
            ]);
        }
        $device['open_closure'] = $status;
        $device->save();
    }

    // 检查是否在围栏之内
    public function checkdevicerange()
    {
        $imei = $this->request->param("imei", '', "string");
        $device_model = new DeviceModel();
        $device = $device_model->where("imei", $imei)->find();
        $device_user_model = new DeviceUserModel();
        $device_user = $device_user_model->where("imei", $imei)->find();
        if (!$device_user) {
            return json_encode([
                'status' => false,
                'msg' => '设备没有被绑定',
            ]);
        }
        $uid = $device_user['uid'];
        $user_model = new UserModel();
        $user = $user_model->where("id", $uid)->find();
        if (!$user) {
            return json_encode([
                'status' => false,
                'msg' => '找不到用户',
            ]);
        }
        $latitude = $user['latitude'];
        $longitude = $user['longitude'];
    }

    public function setCommand()
    {
        $imei = $this->request->param("imei", '', "string");
        // $openid = $this->request->param("openid", '', "string");
        $uid = $this->request->param("uid", 0, "int");
        $command = $this->request->param("command", '', "string");
        // // $data['openid'] = $openid;
        // $data['uid'] = $uid;
        // $data['time'] = time();
        // $data['imei'] = $imei;
        // $data['command'] = $command;
        // $data['status'] = 0;
        // $commandModel = new CommandModel();
        // $commandModel->save($data);
        $cmd = $imei . '&&' . $command;
        $rt = WeixinController::execcommand($cmd);
        if ($rt == true) {
            return json_encode([
                'status' => true,
                'msg' => '发送成功',
            ]);
        } else {
            return json_encode([
                'status' => false,
                'msg' => '发送失败',
            ]);
        }
    }

    // 设置追踪模式
    public function setFollowmodel()
    {
        $imei = $this->request->param("imei", '', "string");
        // $openid = $this->request->param("openid", '', "string");
        $uid = $this->request->param("uid", 0, "int");
        $flag = $this->request->param("flag", 0, "int");
        $command = $this->request->param("command", '', "string");
        // $data['openid'] = $openid;
        // $data['uid'] = $uid;
        // $data['time'] = time();
        // $data['imei'] = $imei;
        // $data['command'] = $command;
        // $data['status'] = 0;
        // $commandModel = new CommandModel();
        // $commandModel->save($data);

        // $devicemodel = new DeviceModel();
        // $devicemodel->where([
        //     'imei' => $imei,
        // ])->update([
        //     'is_follow' => $flag,
        // ]);

        $WeixinController = new WeixinController();
        $cmd = $imei."&&".$command;
        $res = $WeixinController->execcommand($cmd);
        return json_encode([
            'status' => true,
            'msg' => $res,
        ]);
    }

    // 充值
    public function charge()
    {
        $item_id = $this->request->param("item_id", 0, "int");
        $uid = $this->request->param("uid", 0, "int");
        $itemmodel = new ItemModel();
        $item = $itemmodel->find($item_id);
        $ordermodel = new OrderModel();
        $ordermodel['create_time'] = time();
        $ordermodel['item_id'] = $item['id'];
        $ordermodel['status'] = 0;
        $ordermodel['uid'] = $uid;
        $ordermodel->save();
        $usermodel = new $userModel();
        $user = $usermodel->find($uid);

        $device_id = $this->request->param("device_id", 0, "int");
        $deviceModel = new DeviceModel();
        $device = $deviceModel->find($device_id);
        $charge_num = $item['specifi'];
        $num = intval($item['specifi']);

        if ($item['type'] == 1) {
            // 年费
            strtotime('+$charge_num month', $device['effect_time']);
            $expire = date("Y-m-d H:i:s", $num);
            $device['effect_time'] = date("Y-m-d H:i:s", strtotime($expire));
            $device->save();
        } else {
            $device['text_number'] += $item['specifi'];
            $device->save();
        }
        return json_encode([
            'status' => true,
            'msg' => '充值成功',
        ]);
    }

    // 获取验证码
    public function get_verification_code()
    {
        $mobile = $this->request->param("mobile", '', "string");
        $code = cmf_get_verification_code($mobile);
        return json_encode([
            'status' => true,
            'msg' => '充值成功',
            'verification_code' => $code,
        ]);
    }

    // 编辑设备资料
    public function editDeviceInfo()
    {
        $id = $this->request->param("device_id", 0, "int");
        $data['uid'] = $this->request->param("uid", 0, "int");
        $data['contract'] = $this->request->param("contract", 0, "string");
        $data['contract_phone'] = $this->request->param("contract_phone", 0, "string");
        $data['device_phone'] = $this->request->param("device_phone", 0, "string");
        $data['device_name'] = $this->request->param("device_name", 0, "string");
        // $data['create_time'] = time();
        $data['status'] = 0;
        $device_model = new DeviceModel();
        $res = $device_model->where([
            'id' => $id,
        ])->update($data);
        return json_encode([
            'status' => true,
            'msg' => '保存成功',
        ]);
    }

    // 过去设备详情
    public function getDeviceDetailInfo()
    {
        $device_id = $this->request->param("device_id", 0, "int");
        $device_model = new DeviceModel();
        $device = $device_model->find($device_id);
        $device['end_time'] = date("Y.m.d", $device['effect_time']);
        $device['start_time'] = date("Y.m.d", $device['create_time']);
        return json_encode($device);
    }

    // 獲取用戶id
    public function getUserid()
    {
        $umodel = new UserModel();
        $token = $this->request->param("token", '', "string");
        $openid = $this->request->param("openid", '', "string");
        $where = [];
        if (!empty($token)) {
            $where['token'] = $token;
        } elseif (!empty($openid)) {
            $where['openid'] = $openid;
        } else {
            return json_encode([
                'status' => false,
                'msg' => '参数无效',
            ]);
        }
        $user = $umodel->where($where)->find();
        return json_encode([
            'status' => true,
            'msg' => '获取成功',
            'data' => $user['id'],
        ]);
    }

    // 解密用户信息
    public function encryptedData()
    {
        // $encryptedData = $this->request->param("encryptedData", '', "string");
        // $appid = $this->request->param("appId", '', "string");
        $code = $this->request->param("code", '', "string");
        // $iv = $this->request->param("iv", '', "string");
        $WeixinController = new WeixinController();
        $sessionKey = $WeixinController->getsessionkey($code);
        // echo VENDOR_PATH . "wxcrypt/wxBizDataCrypt.php";die;
        // include_once VENDOR_PATH . "wxcrypt/wxBizDataCrypt.php";
        // $pc = new \WXBizDataCrypt($appid, "4YL/ic+Z3TbC/4D0GUsusw==");
        // $errCode = $pc->decryptData($encryptedData, $iv, $data);

        // if ($errCode == 0) {
        // return $data;
        // } else {
        // return $errCode;
        // }
    }

    // 獲取用戶id
    public function getUserinfo()
    {
        $umodel = new UserModel();
        $userid = $this->request->param("userid", 0, "int");
        $user_token = $this->request->param("user_token", 0, "string");
        if (!$userid && !$user_token) {
            return json_encode([
                'status' => false,
                'msg' => '参数无效',
            ]);
        }
        if ($userid) {
            $user = $umodel->find($userid);
        }
        if ($user_token) {
            $user = $umodel->where([
                'token' => $user_token,
            ])->find();
        }

        return json_encode([
            'status' => true,
            'msg' => '获取成功',
            'data' => $user,
        ]);
    }

    // 设置用户当前的设备
    public function setCurrentDevice()
    {
        $device_id = $this->request->param("device_id", 0, "int");
        $uid = $this->request->param("uid", 0, "int");
        $UserCurrentDeivce = UserCurrentDeivceModel::where([
            'uid' => $uid,
        ])->find();
        if ($UserCurrentDeivce) {
            $UserCurrentDeivceModel['d_id'] = $device_id;
            UserCurrentDeivceModel::where([
                'uid' => $uid,
            ])->update([
                'd_id' => $device_id,
            ]);
        } else {
            $UserCurrentDeivceModel = new UserCurrentDeivceModel();
            $UserCurrentDeivceModel->d_id = $device_id;
            $UserCurrentDeivceModel->uid = $uid;
            $UserCurrentDeivceModel->save();
        }
        return json_encode([
            'status' => true,
            'msg' => '设置成功',
        ]);
    }

    // 获取充值信息列表
    public function getItemList()
    {
        $type = $this->request->param("type", 1, "int");
        $list = ItemModel::where([
            'type' => $type,
        ])->select();
        return json_encode([
            'status' => true,
            'msg' => '获取成功',
            'data' => $list,
        ]);
    }

    public function getuserdevicelist()
    {
        $uid = $this->request->param("userid", 0, "int");
        $data = Db::table('erxi_user_current_deivce')->alias('a')
            ->join([
                'erxi_device' => 'b',
            ], 'b.id=a.d_id')
            ->
        // ->join(['erxi_device_data_current'=>'c'], 'c.imei=b.imei',"left")
            where([
            'a.uid' => $uid,
        ])
            ->
        // ->order("c.time desc")
            // ->limit(1)
            field("b.*")
            ->find();
        $imei = $data['imei'];

        $time_data = 1000 * (time() - (3600 * 3));

        $list = Db::table('erxi_device_data')->alias('a')
            ->join([
                'erxi_device_user' => 'c',
            ], 'c.imei=a.imei', "left")
            ->where([
                'a.imei' => $imei,
                'a.create_time' => [
                    'gt',
                    $time_data,
                ],
            ])
            ->order("a.create_time")
            ->field("a.*,FROM_UNIXTIME(a.create_time/1000,'%Y-%m-%d %H:%i:%s') data_time")
            ->select();
        if (sizeof($list) == 0) {
            $list = Db::table('erxi_device_data')->alias('a')
                ->join([
                    'erxi_device_user' => 'c',
                ], 'c.imei=a.imei', "left")
                ->where([
                    'a.imei' => $imei,
                ])
                ->order("a.create_time desc")
                ->limit(1)
                ->field("a.*,FROM_UNIXTIME(a.create_time/1000,'%Y-%m-%d %H:%i:%s') data_time")
                ->select();
        }
        // echo Db::table('erxi_device_data')->getLastSql();die;

        $device_list = Db::table('erxi_device_user')->join("erxi_device", "erxi_device.id=erxi_device_user.device_id")
            ->field("erxi_device.*")
            ->where([
                'erxi_device_user.uid' => $uid,
            ])
            ->select();

        return json_encode([
            'status' => true,
            'msg' => '获取成功',
            'device_last' => $data,
            'device_data_list' => $list,
            'device_list' => $device_list,
        ]);
    }

    public function getcurrentDevice()
    {
        $uid = $this->request->param("userid", 0, "int");
        $data = Db::table('erxi_user_current_deivce')->alias('a')
            ->join([
                'erxi_device' => 'b',
            ], 'b.id=a.d_id')
            ->
        // ->join(['erxi_device_data_current'=>'c'], 'c.imei=b.imei',"left")
            where([
            'a.uid' => $uid,
        ])
            ->
        // ->order("c.time desc")
            // ->limit(1)
            find();
        $imei = $data['imei'];

        $list = Db::table('erxi_device_data')->alias('a')
            ->
        // ->join(['erxi_device_data_current'=>'c'], 'c.imei=b.imei',"left")
            where([
            'a.imei' => $imei,
        ])
            ->order("a.time")
            ->limit(100)
            ->select();

        return json_encode([
            'status' => true,
            'msg' => '获取成功',
            'device_last' => $data,
            'device_data_list' => $list,
        ]);
    }

    // 设置设备围栏
    public function setDevicehome()
    {
        $imei = $this->request->param("imei", '', "string");
        $flag = $this->request->param("flag", 0, "boolean");
        // $command = $this->request->param("command", '', "string");
        $latitude = $this->request->param("latitude", '', "string");
        $longitude = $this->request->param("longitude", '', "string");
        $uid = $this->request->param("uid", 0, "int");
        $devicemodel = new DeviceModel();
        $devicemodel->where([
            'imei' => $imei,
        ])->update([
            'is_home' => $flag,
            'center_latitude' => $latitude,
            'center_longitude' => $longitude,
        ]);

        // $data['uid'] = $uid;
        // $data['time'] = time();
        // $data['imei'] = $imei;
        // $data['command'] = $command;
        // $data['status'] = 0;
        // $commandModel = new CommandModel();
        // $commandModel->save($data);

        return json_encode([
            'status' => true,
            'msg' => '设置成功',
        ]);
    }

    public function uploadDeviceAvatar()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('avatar');
        $id = request()->param("device_id");
        // 移动到框架应用根目录/public/uploads/ 目录下
        if ($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if ($info) {
                // 成功上传后 获取上传信息
                // 输出 jpg
                // echo $info->getExtension();
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                // echo $info->getSaveName();
                // 输出 42a79759f284b767dfcb2a0197904287.jpg
                // echo $info->getFilename();
                $path = request()->domain() . request()->root() . "/uploads/" . $info->getSaveName();
                $path = str_replace('\\', "/", $path);
                $model = new DeviceModel();
                $model->where([
                    'id' => $id,
                ])->update([
                    'avatar' => $path,
                ]);
                echo json_encode([
                    'status' => true,
                    'msg' => '上传成功',
                    'path' => $path,
                ]);
            } else {
                // 上传失败获取错误信息
                echo $file->getError();
            }
        }
    }

    public function changeDeviceName()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $id = request()->param("device_id");
        $name = request()->param("name");
        // 移动到框架应用根目录/public/uploads/ 目录下
        $model = new DeviceModel();
        $model->where([
            'id' => $id,
        ])->update([
            'device_name' => $name,
        ]);
        $this->updatepetinfo();
        echo json_encode([
            'status' => true,
            'msg' => '保存成功',
        ]);
    }

    public function getpetlist()
    {
        $device_id = $this->request->param("device_id", 0, "int");
        $uid = $this->request->param("userid", 0, "int");
        $data = Db::table('erxi_pet')->where([
            'uid' => $uid,
            'device_id' => $device_id,
        ])->find();
        return json_encode([
            'status' => true,
            'msg' => '获取成功',
            'pet_list' => $data,
        ]);
    }

    public function updatepetinfo()
    {
        $device_id = $this->request->param("device_id", 0, "int");
        $uid = $this->request->param("userid", 0, "int");
        $name = $this->request->param("name", '', "string");
        $age = $this->request->param("age", '', "string");
        $sex = $this->request->param("sex", '', "string");
        $varieties = $this->request->param("varieties", '', "string");
        if (!$device_id || !$uid) {
            return json_encode([
                'status' => false,
                'msg' => '参数错误',
            ]);
        }
        $pet = PetModel::where([
            'device_id' => $device_id,
            'uid' => $uid,
        ])->find();
        if ($pet) {
            if ($name) {
                $pet->name = $name;
            }
            if ($age) {
                $pet->age = $age;
            }
            if ($sex != '') {
                $pet->sex = $sex;
            }
            if ($varieties) {
                $pet->varieties = $varieties;
            }
            $pet->save();
        } else {
            $pet = new PetModel();
            $pet->uid = $uid;
            $pet->device_id = $device_id;
            $pet->name = $name;
            $pet->age = $age;
            $pet->sex = $sex;
            $pet->varieties = $varieties;
            $pet->time = time();
            $pet->save();
        }
        return json_encode([
            'status' => true,
            'msg' => '保存成功',
        ]);
    }

    // 获取用户的openid
    public function getOpenidByCode()
    {
        $code = $this->request->param("code", '', "string");
        if (!$code) {
            return json_encode([
                'status' => false,
                'msg' => '参数错误',
            ]);
        }
        $appid = config("appid");
        $secret = config("secret");
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $json = json_decode(cmf_curl_get($url), true);
        // $session_key = $json['session_key'];
        $openid = $json['openid'];
        return json_encode([
            'status' => true,
            'msg' => '获取成功',
            'data' => $openid,
        ]);
    }

    //搜索地点位置列表
    public function getLocationListByKeyword()
    {
        $keyword = $this->request->param("keyword", '', "string");
        if(!$keyword){
            return json_encode(['status' => -1, 'msg' => '参数错误']);
        }
        $key = "VMOBZ-FEIK6-R5KSZ-MGHQO-G2IXO-ZCBCX";
        $url = "https://apis.map.qq.com/ws/place/v1/search?boundary=region(北京,0)&keyword=$keyword&page_size=20&page_index=1&orderby=_distance&key=$key";
        $json = json_decode(file_get_contents($url), true);
        if ($json['status'] == 0) {
            return json_encode(['status' => $json['status'], 'msg' => $json['message'], 'data' => $json['data']]);
        } else {
            return json_encode(['status' => $json['status'], 'msg' => $json['message']]);
        }
    }

    public function updateUserInfo(){
        $uid = $this->request->param("uid", 0, "int");
        $nickname = $this->request->param("nickname", '', "string");
        $avatar = $this->request->param("avatar", '', "string");
        $user = Db::table("erxi_user")->find($uid);
        $user['user_nickname'] = $nickname;
        $user['avatar'] = $avatar;
        $res = Db::table("erxi_user")->where([
            'id' => $uid,
        ])->update($user);
        // if($res){
        //     return json_encode(['msg'=>'更新成功'])
        // }
    }
}
